package com.zbu.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zbu.common.core.constants.CacheConstants;
import com.zbu.common.core.enums.ResultCode;
import com.zbu.common.redis.service.RedisService;
import com.zbu.common.security.exception.ServiceException;
import com.zbu.friend.domain.question.Question;
import com.zbu.friend.mapper.question.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class QuestionCacheManager {
    @Autowired
    RedisService redisService;
    @Autowired
    QuestionMapper questionMapper;
    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        List<Question>questionList=questionMapper.selectList(new LambdaQueryWrapper<Question>().
                select(Question::getQuestionId).orderByDesc(Question::getCreateTime));
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<Long>questionIdList=questionList.stream().map(Question::getQuestionId).toList();
        redisService.rightPushAll(CacheConstants.QUESTION_LIST,questionIdList);

    }

    public Long preQuestion(Long quesstionId) {
        Long index=redisService.indexOf(CacheConstants.QUESTION_LIST,quesstionId);
        if(index==0){
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.index(CacheConstants.QUESTION_LIST,index-1,Long.class);
    }

    public Long nextQuestion(Long quesstionId) {
        Long index=redisService.indexOf(CacheConstants.QUESTION_LIST,quesstionId);
        Long listSize = getListSize()-1;
        if(index==listSize){
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.index(CacheConstants.QUESTION_LIST,index-1,Long.class);
    }
}
